var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var path = require('path');
var fs = require('fs');
var silly = require('silly-datetime');
var destpath = "./public/images/";
var urlpath = "/images/";


/* GET photo page. */
router.get('/', function (req, res, next) {
    let arr = fs.readdir(destpath, function(err, files) {
      if (err) {
        console.log('读取文件夹错误:', err);
      } else {
        var photos = [];
        files.forEach(fileName => {
          let item = {
            'name':'',
            'path':'',
            'file_name':''
          };
          item.name = findFileName(fileName);
          item.path = urlpath + fileName;
          item.file_name = fileName;
          photos.push(item);
        });
        res.render('photos', { title: 'Photos', data: photos });
      }
    });
});

router.get('/upload', function (req, res, next) {
  res.render('photos/upload', { title: '图片上传' });
});

router.post('/submit', function (req, res, next) {
  var form = new multiparty.Form();
  form.encoding = 'utf-8';
  form.uploadDir = destpath;
  form.maxFilesSize = 20 * 1024 * 1024;
  form.parse(req, (err, fields, files) => {
    if (err) {
      console.log('解析上传文件错误:', err);
    } else {
      var originalFilename = files.file[0].originalFilename;
      var fileType = findFileType(originalFilename);
      var fileName = originalFilename;
      if (fields.name != null) {
        fileName = fields.name[0] + fileType;
      }
      var uploadedPath = files.file[0].path;
      var newFileName = destpath + formatDate(new Date()) + "_" + fileName;
      fs.rename(uploadedPath, newFileName, (err) => {
        if (err) {
          console.log('重命名文件错误:', err);
        }
        res.redirect('/photo');
      });
    }
  });

});

router.get('/download', function (req, res, next) {
  var filePath = destpath + req.query.fileName;
  if (fs.existsSync(filePath)) {
    var absPath = path.resolve(filePath);
    res.sendFile(absPath);
    res.download(absPath);
  } else {
    res.send('文件不存在');
  }
});

function findFileType(originalFilename) {
  var lastIndex = originalFilename.lastIndexOf('.');
  if (lastIndex != -1) {
    return originalFilename.substring(lastIndex);
  }
  return originalFilename;
}

function findFileName(inputFileName) {
  var lastIndex = inputFileName.lastIndexOf('.');
  if (lastIndex != -1) {
    return inputFileName.substring(0, lastIndex);
  }
  return inputFileName;
}

function formatDate(date) {
  if (date == null) {
    return "";
  }
  return silly.format(date, 'YYYYMMDD-HHmmss');
}

module.exports = router;